package dept_rooms

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ DeptRoomsModel = (*customDeptRoomsModel)(nil)

type (
	// DeptRoomsModel is an interface to be customized, add more methods here,
	// and implement the added methods in customDeptRoomsModel.
	DeptRoomsModel interface {
		deptRoomsModel
		FindByDept(ctx context.Context, deptId string) ([]DeptRooms, error)
		FindByDeptRooms(ctx context.Context, deptId string) ([]FDeptRoomsModel, error)
	}

	customDeptRoomsModel struct {
		*defaultDeptRoomsModel
	}
)

// NewDeptRoomsModel returns a model for the database table.
func NewDeptRoomsModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) DeptRoomsModel {
	return &customDeptRoomsModel{
		defaultDeptRoomsModel: newDeptRoomsModel(conn, c, opts...),
	}
}

func (m *defaultDeptRoomsModel) FindByDept(ctx context.Context, deptId string) ([]DeptRooms, error) {
	var resp []DeptRooms
	query := fmt.Sprintf("select %s from %s where `deptid` = ?", deptRoomsRows, m.table)
	err := m.QueryRowsNoCacheCtx(ctx, &resp, query, deptId)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultDeptRoomsModel) FindByDeptRooms(ctx context.Context, deptId string) ([]FDeptRoomsModel, error) {
	var resp []FDeptRoomsModel
	query := fmt.Sprintf("select d.deptid,d.deptname,r.roomid,r.roomname from dept_rooms dr,rooms r,depts d where dr.roomid=r.roomid and dr.deptid=d.deptid and d.deptid=?")
	err := m.QueryRowsNoCache(&resp, query, deptId)
	switch err {
	case nil:
		return resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

type FDeptRoomsModel struct {
	DeptId   sql.NullString `db:"deptid"`   // 科室id
	DeptName sql.NullString `db:"deptname"` // 科室名称
	RoomId   sql.NullString `db:"roomid"`   // 诊室id
	RoomName sql.NullString `db:"roomname"` //诊室名称
}
